package cn.iocoder.yudao.module.javainfo.events.listener;

import cn.iocoder.yudao.module.javainfo.controller.admin.financialflow.vo.FinancialFlowSaveReqVO;
import cn.iocoder.yudao.module.javainfo.dal.dataobject.user.UserDO;
import cn.iocoder.yudao.module.javainfo.enums.AmountTypeEnum;
import cn.iocoder.yudao.module.javainfo.enums.TransactionTypeEnum;
import cn.iocoder.yudao.module.javainfo.events.UserCreatedEvent;
import cn.iocoder.yudao.module.javainfo.service.financialflow.FinancialFlowService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import javax.annotation.Resource;

@Component
public class UserCreatedEventListener {
    @Resource
    private FinancialFlowService financialFlowService;

    @Async
    @TransactionalEventListener(classes = UserCreatedEvent.class, phase = TransactionPhase.AFTER_COMMIT)
    public void createUserFinancial(UserCreatedEvent event) {
        UserDO user = event.getDto();
        // 插入金额流水表，默认金额为0
        FinancialFlowSaveReqVO userFinancialDO = new FinancialFlowSaveReqVO();
        userFinancialDO.setUserId(user.getId());
        //默认订单号-时间戳和用户id
        userFinancialDO.setOrderNumber(String.valueOf(user.getId() + System.currentTimeMillis()));
        userFinancialDO.setAmountType(AmountTypeEnum.of(1).getValue());
        userFinancialDO.setTransactionChannel(TransactionTypeEnum.of(0).getValue());
        userFinancialDO.setAmount(0L);
        userFinancialDO.setBalanceAfter(0L);
        financialFlowService.createFinancialFlow(userFinancialDO);
    }
}
